package cn.edu.lingnan.part.controller;

import cn.edu.lingnan.part.entity.Admin;
import cn.edu.lingnan.part.entity.AdminQuery;
import cn.edu.lingnan.part.entity.Student;
import cn.edu.lingnan.part.entity.common.CommonResult;
import cn.edu.lingnan.part.listener.StudentExcelListener;
import cn.edu.lingnan.part.service.AdminService;
import cn.edu.lingnan.part.service.StudentService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;

/**
 * (Admin)表控制层
 *
 * @author makejava
 * @since 2020-05-25 21:59:15
 */
@Controller
@RequestMapping("admin")
public class AdminController {

    Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 服务对象
     */
    @Resource
    private AdminService adminService;

    @Autowired
    private StudentService studentService;
//    @Resource
//    private Admin admin;


//    @RequestMapping("tologin")
//    这是Result风格的api
    @RequestMapping("tologin")
    public String toLogin(){

        //trace是追踪日志
        logger.trace("这是。。。trace（跟踪/追踪）日志");

        //trace是debug日志
        logger.debug("这是。。。。debug日志");

        //SpringBoot默认使用的是info级别以上的
        //这是自定义信息
        logger.info("这是。。。info(自定义)日志");

        //这是警告信息
        logger.warn("这是。。。warn（警告）日志");

        //这是错误信息
        logger.error("这是。。。error日志");
//        return "redirect:/login.html";
        return "login";
    }


    @RequestMapping("toWelcome")
    public String toWelcom(){
        return "page/welcome-1";
    }

    @RequestMapping("toList")
    public String toList(){
        return "user/admin_list";
    }

    @RequestMapping("/")
    public String toAdd(Model model){
        model.addAttribute("admin",new Admin());
        return "user/admin_add";
    }

    @RequestMapping("toEdit")
    public String toEdit( Integer id, Model model){

        System.out.println(id);
        Admin admin = adminService.queryById(id);
        //将调出来页面设置为admin修改的页面
        model.addAttribute("admin", admin);
        return "user/admin_add";
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("getById")
    @ResponseBody
    public Admin getById(Integer id) {
        return this.adminService.queryById(id);
    }




    /**
     * @param admin 主键
     *  @return 单条数据对象
     */
    @PostMapping("insert")
    @ResponseBody
    public Admin insert(Admin admin){
        return adminService.insert(admin);
    }

    /**
     * @Param account,password
     * @return 单条数据对象
     */



//    @PostMapping("login")
    @PostMapping(value = "login")
    public String login(String account, String password, Model model, HttpSession session) throws ParseException {

        Admin admin = adminService.login(account, password);
        System.out.println(admin.getLastLoginData());
        admin.setRegData(new Date());
//        这种格式传不进去lastLoginData
//
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = null;
//        date = df.parse(df.format(new Date()));
        session.setAttribute("loginAccount",admin.getAccount());
        Date date = new Date();
        System.out.println(date);
        adminService.updateTime(date, admin.getAccount());
        System.out.println(admin.getLastLoginData());

        return "index";
    }

    /**
     * 查询全部
     * @param page
     * @param limit
     * @param admin
     * @return
     */

    @PostMapping("queryAll")//这里也是提交一个表单申请，所以也是用post请求
    @ResponseBody//返回的是数据
    public Object queryAll(Integer page, Integer limit, AdminQuery admin){

        CommonResult result = new CommonResult<>();
        IPage<Admin> iPage = adminService.queryAllByLimit(page,limit,admin);
        result.setCode(0);
        result.setCount(iPage.getTotal());
        result.setData(iPage.getRecords());
        return result;
    }

    /**
     * 添加管理员,因为添加编辑用的是同一个页面，所以需要操作进行一个判断
     * 判断当前的操作是添加还是编辑
     * @param admin
     *
     * @return
     */
    @PostMapping("save")
    @ResponseBody
    public Object save(Admin admin) {
        boolean result = false;
        //有一个判断逻辑需要处理，就是判断添加的账号是否已存在
//        Admin admin1 = adminService.queryByAccount(admin.getAccount());
        if (admin.getId() != null) {
//      编辑
        System.out.println("修改成功");
//      model.addAttribute("msg", "该账号已经存在");
            result = adminService.update(admin) > 0;
        } else {
//            添加
            //设置注册的时间，调用系统时间
            admin.setRegData(new Date());
            //做添加是不会有id的
            result = adminService.insert(admin).getId() != null;
        }
        return result;
    }

//    @DeleteMapping("deleteById") 先使用post请求
    @PostMapping("/{ids}")
    @ResponseBody
    public boolean deleteById(@PathVariable Integer[] ids){
        if (ids == null || ids.length == 0){
            return false;
        }
        System.out.println(Arrays.toString(ids));
        adminService.deleteById(Arrays.asList(ids));
        return true;
    }

    /**
     * 处理文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ResponseBody
    public Object upload(MultipartFile file) {
        CommonResult result = new CommonResult<>();
        try {
            EasyExcel.read(file.getInputStream(), Student.class, new StudentExcelListener(studentService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            result.setMsg("Excel上传出错!");
        }
        result.setData(file.getOriginalFilename());
        return result;
    }

}